package c0907m.group2.aitsm.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Author: LongDH
 * Date: 4/29/11
 * Time: 3:29 PM
 * <p/>
 * Simply format the log messages.
 */
public class SimpleLogFormatter extends Formatter {
    Date dat = new Date();
    private final static String format = "{0,date,dd/MM/yyyy} {0,time,HH:mm:ss}";
    private MessageFormat formatter;

    private Object args[] = new Object[1];

    // Line separator string.  This is the value of the line.separator
    // property at the moment that the SimpleFormatter was created.
    private String lineSeparator =
            (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));

    public SimpleLogFormatter() {
        super();
    }

    public String format(LogRecord record) {
        StringBuffer sb = new StringBuffer();
        // Minimize memory allocations here.
        dat.setTime(record.getMillis());
        args[0] = dat;
        StringBuffer text = new StringBuffer("<");
        if (formatter == null) {
            formatter = new MessageFormat(format);
        }
        formatter.format(args, text, null);
        sb.append(text);
        sb.append("> ");

        String message = formatMessage(record);
        sb.append(message);
        sb.append(lineSeparator);

        if (record.getThrown() != null) {
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                record.getThrown().printStackTrace(pw);
                pw.close();
                sb.append(sw.toString());
            } catch (Exception ex) {
            }
        }
        return sb.toString();
    }
}
